package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.PageQuery;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.PageVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public List<User> queryUsers(String username, Integer status, Long min, Long max) {
        return lambdaQuery().like(User::getUsername, username).list();
    }

    @Override
    public PageVO<UserVO> queryUserByPage(PageQuery query) {
        // 1.分页条件
        Page<User> p = query.toMpPageDefaultSortByUpdate();
        // 2.查询
        page(p);
        // 3.返回
        return new PageVO<>(p, user -> {
            UserVO vo = BeanUtil.copyProperties(user, UserVO.class);
            String username = vo.getUsername();
            vo.setUsername(username.substring(0, username.length()- 4) + "****");
            return vo;
        });
    }

    @Override
    @Transactional
    public void deductBalance(Long id, Integer money) {
        User user = getById(id);
        if(user==null||user.getStatus().getValue()==2){
            throw new RuntimeException("用户状态异常");
        }
        if(user.getBalance()<money){
            throw new RuntimeException("用户状态异常");
        }
        int remainBalance=user.getBalance()-money;
        lambdaUpdate().set(User::getBalance,remainBalance)
                .set(remainBalance==0,User::getStatus,2)
                .eq(User::getId,id)
                .eq(User::getBalance,user.getBalance())//乐观锁
                .update();

//        baseMapper.decuctBalance(id,money);

    }

    @Override
    public List<User> queryUserByIds(String name, Integer status, Integer minBalance, Integer maxBalance) {
        return lambdaQuery().like(name!=null,User::getUsername,name)
                            .eq(status!=null,User::getStatus,status)
                            .ge(minBalance!=null,User::getBalance,minBalance)
                            .le(maxBalance!=null,User::getBalance,maxBalance)
                .list();

    }

    @Override
    public UserVO queryUserAndAddressById(Long id) {
        //查用户
        User user = getById(id);
        if(user == null || user.getStatus().getValue() == 2){
            throw new RuntimeException("用户状态异常！");
        }
//        2.查询地址
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
        //3.封装
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        if(CollUtil.isNotEmpty(addresses)){
            userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        }
        return userVO;
    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        //1.查询用户
        List<User> users = listByIds(ids);
        if(CollUtil.isEmpty(users)){
            return Collections.emptyList();
        }
        //2.查地址
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        List<Address> addresses = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
        List<AddressVO> addressVOList = BeanUtil.copyToList(addresses, AddressVO.class);
        Map<Long, List<AddressVO>> addressMap =new HashMap<>(0);
        if(CollUtil.isNotEmpty(addressVOList)){
            addressMap = addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }

        //3.转VO
        List<UserVO> list=new ArrayList<>(users.size());
        for (User user : users) {
            UserVO vo = BeanUtil.copyProperties(user, UserVO.class);
            list.add(vo);
            vo.setAddresses(addressMap.get(user.getId()));
        }
        return list;
    }

    @Override
    public PageDTO<UserVO> queryUsersByPage(UserQuery query) {
        String name=query.getName();
        Integer status = query.getStatus();
        //1.构建分页查询
//        Page<User> page = Page.of(query.getPageNo(), query.getPageSize());
//
//        if(StrUtil.isNotBlank(query.getSortBy())){
//            page.addOrder(new OrderItem(query.getSortBy(),query.getIsAsc()));
//
//        }else {
//            page.addOrder(new OrderItem("update_time",false));
//        }
        Page<User> page = query.toMpPageDefaultSortByUpdate();

        //2.分页查询
        Page<User> p = lambdaQuery().like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);

        //3.封装结果
//        PageDTO<UserVO> dto=new PageDTO<>();
//        dto.setTotal(p.getTotal());
//        dto.setPages(p.getPages());
//
//        List<User> records = p.getRecords();
//
//        if(CollUtil.isEmpty(records)){
//            dto.setList(Collections.emptyList());
//            return dto;
//        }
//
//        dto.setList(BeanUtil.copyToList(records,UserVO.class));
//        return dto;

//        return PageDTO.of(p,UserVO.class);

        return PageDTO.of(p,user -> BeanUtil.copyProperties(user,UserVO.class));
    }
}
